package vn.vayme.cash.newworld.location;

import android.Manifest;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;


import com.cash.lemoloan.statisticlib.StatisticContant;
import vn.vayme.cash.newworld.MyApplication;
import vn.vayme.cash.newworld.Utils.PermissionUtil;

import java.util.ArrayList;
import java.util.List;

import com.cash.lemoloan.statisticlib.Utils.PreferencesUtil;


public class LocationTask extends AsyncTask<String,Void,Void> {
    private List<ILocation> mLocations = new ArrayList<>();
    private Handler mCancleHandler;                                 //定时取消的handler
    private boolean isLoop = false;                                 //是否是循环刷新定位调用的service
    private static final long LOOP_LOCATION_TIME = 60*60 * 1000;  //循环定位时间间隔,默认一小时
    private long LOCATION_OVERTIME = 180 * 1000;                 //设置定位超时时间，默认为180秒
    private long mLocationOverTime;
    private LocationData mLocationDataTemp = null;
    private int mLocationFailCount = 0;
    private int mLocationSuccessCount = 0;
    private boolean mLocationSuccess = false;                   //是否定位成功
    private boolean mLocationFail = false;                   //是否定位失败
    private boolean isFastLocation = false;              //是否以最快速度返回定位信息

    public LocationTask(Bundle bundle){

        if (PermissionUtil.checkPermissionsGranted(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            mLocations.add(new GoogleLocation(MyApplication.getApplication(),locationCallback));
            mLocations.add(new SystemLocation(MyApplication.getApplication(), locationCallback));
            //开始定位操作，遍历执行每个定位sdk
            for (ILocation location : mLocations) {
                location.startLocation();
            }

        }

        if(null != bundle){
            isLoop = bundle.getBoolean("loop",false);              //获取是否是循环刷新位置
            isFastLocation = bundle.getBoolean("isFastLocation",false);        //获取是否是以最快时间获取定位位置的方式
            mLocationOverTime = bundle.getLong("overtime",LOCATION_OVERTIME);      //获取设置的超时时间
        }
        mCancleHandler = new Handler();
        if (mCancleHandler !=null)
            postToClose();
    }
    @Override
    protected Void doInBackground(String... strings) {

        return null;
    }

    private void postToClose(){

        if (mCancleHandler != null){
            mCancleHandler.removeCallbacksAndMessages(null);
        }
        //延迟等待定位，没返回则关闭服务
        mCancleHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mLocationDataTemp){
                    locationSuccess(mLocationDataTemp);
                }else {
                    locationFail(0);
                }
            }
        }, mLocationOverTime);
    }

    /**
     * 传递定位结果
     * @param isSuccess
     */
    private void locationResult(boolean isSuccess){

    }

    private ILocationCallback locationCallback = new ILocationCallback() {
        @Override
        public synchronized void onLocationSuccess(LocationData locationData) {
            //定位成功但是数据为0的情况
            if (0 == Double.valueOf(locationData.latitude) || 0 == Double.valueOf(locationData.longitude)){

                //以防出现错误，定位成功但是经纬度为0
                mLocationFailCount ++;
                if (mLocationFailCount == mLocations.size()){
                    //如果所有定位方式全部定位失败

                    locationFail(1);
                }
                return;
            }
            mLocationSuccessCount ++ ;
            //定位成功的情况google优先原则
            if (isFastLocation || "google".equals(locationData.way)){
                locationSuccess(locationData);
            }else {
                if ((mLocationSuccessCount + mLocationFailCount) == mLocations.size()){
                    locationSuccess(locationData);
                }else {
                    mLocationDataTemp = locationData;
                }
            }
        }



        @Override
        public synchronized void onLocationFailed(LocationErrorType locationErrorType, String way, String message) {
            mLocationFailCount ++;
            if (mLocationFailCount + mLocationSuccessCount == mLocations.size()){
                if (null != mLocationDataTemp){
                    locationSuccess(mLocationDataTemp);
                }else {
                    //如果所有定位方式全部定位失败
                    locationFail(2);

                }
            }
        }
    };

    private void locationFail(int status){
        if (!mLocationFail){
            mLocationFail = true;
            if (!isLoop){
                locationResult(false);
            }
        }
        close();
    }

    private void locationSuccess(LocationData locationData){
        if(locationData != null){
            StatisticContant.latitude = locationData.latitude;
            StatisticContant.longitude = locationData.longitude;
            PreferencesUtil.putString(StatisticContant.LATITUDE_FLAG,locationData.latitude);
            PreferencesUtil.putString(StatisticContant.LONGITUDE_FLAG,locationData.longitude);
        }

        if (!mLocationSuccess){
            mLocationSuccess = true;
            saveData(locationData);
            if (!isLoop){
                locationResult(true);
            }
        }
        close();
    }

    private void saveData(final LocationData locationData){
        StatisticContant.latitude = locationData.latitude;
        StatisticContant.longitude = locationData.longitude;
/*         List<Address> addresses; Geocoder geocoder = new Geocoder(UIUtils.getContext(), Locale.getDefault());
        String addStr = null;
       try {
            addresses = geocoder.getFromLocation(Double.valueOf(latitude),Double.valueOf(longitude), 1);
            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String zipCode = addresses.get(0).getPostalCode();
            String country = addresses.get(0).getCountryCode();
            addStr = address + "," + city + "," + state + "," + zipCode + "," + country;
            LogUtil.e("addStr " + addStr);
        }
            catch (IOException e) {
            e.printStackTrace();
        }*/



        if (isLoop){
//            StatManager.init(this, new Stat.OnUploadResponseListener() {
//                @Override
//                public void onResult(String s, Stat.Result result) {
//                    StatManager.uploadLoc01(locationData.latitude,locationData.longitude,extras);
//                }
//            });
        }else {
//            StatManager.uploadLoc01(locationData.latitude,locationData.longitude,extras);
        }
    }

    private void close(){
        if (null  != mCancleHandler){
            mCancleHandler.removeCallbacksAndMessages(null);
            mCancleHandler = null;
        }
        for (ILocation location : mLocations) {
            location.closeLocation();
        }
    }

}
